<?php
/**
 * @author Harris
 *砍价
 *
 * @copyright  Copyright (c) 中国追溯
 * @since      File available since Release v1.1
 */
use Shopnc\Tpl;


defined('InShopNC') or exit('Access Invalid!');
class kanjiaControl extends mobileHomeControl {
    public function __construct() {
        parent::__construct();
    }

    public function infoOp() {
        $buyer_id = intval($_GET['buyer_id']);
        $data = array();

        $model_member = Model('member');
        $model_kanjia = Model('p_kanjia');
        $condition = array();
        $_GET['pay_sn']?$condition['pay_sn']=$_GET['pay_sn']:$condition['log_id'] = intval($_GET['kanjia_id']);
        $condition['buyer_id'] = $buyer_id;
        $condition['pay_time'] = array('gt',0);
        $_info = $model_kanjia->getOrderInfo($condition);
        if (!empty($_info) && is_array($_info)) {
            $order_id = $_info['order_id'];
            $goods_id = $_info['goods_id'];
            $_end_time = $_info['end_time']-TIMESTAMP;
            $data['kanjia_end_time'] = 0;
            
            $member_id = $this->getMemberIdIfExists();
            $data['member_id'] = $member_id;
            
            $model_order = Model('order');
            $order_goods = $model_order->getOrderGoodsInfo(array('order_id'=> $order_id));
            if ($buyer_id == $member_id) $data['order_id'] = $order_id;//当前登录会员订单编号
            
            $condition = array();
            $condition['goods_id'] = $goods_id;
            $kanjia_info = $model_kanjia->getGoodsInfo($condition);
            if ($_info['lock_state'] && $_end_time > 0) {
                $data['log_id'] = $_info['log_id'];
                $data['buyer_id'] = $_info['buyer_id'];
                $data['kanjia_end_time'] = $_end_time;
            }
            $data['goods_id'] = $_info['goods_id'];
            $data['min_num'] = $_info['min_num'];
            
            $data['goods_name'] = $order_goods['goods_name'];
            $data['kanjia_price'] = $order_goods['goods_price'];
            $data['goods_image_url'] = cthumb($order_goods['goods_image'], 240);
            
            $data['goods_price'] = $kanjia_info['goods_price'];
            $data['kanjia_name'] = $kanjia_info['kanjia_name'];
            $data['sale_count'] = Model("p_kanjia")->getKanjiaGoodsCount($_info['goods_id']);
            $log_list = array();
            $buyer_type = $_info['buyer_type'];//参团类型:0为团长,其它为参团
            if ($buyer_type) {
                $_info = $model_kanjia->getOrderInfo(array('log_id'=> $buyer_type));
            }
            $log_id = $_info['log_id'];
            if (!empty($_info)) {
                $_array = array();
                $_array['buyer_id'] = $_info['buyer_id'];
                $_array['buyer_name'] = $_info['buyer_name'];
                $_array['buyer_type'] = $_info['buyer_type'];
                $_array['avatar'] = getMemberAvatarForID($_info['buyer_id']);
                $_array['time_text'] = date('Y-m-d H:i:s',$_info['pay_time']);
                $_array['type_text'] = '开团';
                $log_list[] = $_array;
            }
            $condition = array();
            $condition['buyer_type'] = $log_id;
            $condition['goods_id'] = $goods_id;
            $condition['pay_time'] = array('gt',0);
            $list = $model_kanjia->table('order_kanjia')->where($condition)->order('pay_time asc')->select();
            foreach ($list as $k => $_info) {
                $_array = array();
                $_array['buyer_id'] = $_info['buyer_id'];
                $_array['buyer_name'] = $_info['buyer_name'];
                $_array['buyer_type'] = $_info['buyer_type'];
                $_array['avatar'] = getMemberAvatarForID($_info['buyer_id']);
                $_array['time_text'] = date('Y-m-d H:i:s',$_info['pay_time']);
                $_array['type_text'] = '参团';
                $log_list[] = $_array;
            }
            $num = $_info['min_num']-count($log_list);
            $kanjia_price = json_decode($_info['kanjia_price'], true);;
            $data['kanjia_info'] = $kanjia_price;
            $data['num'] = $num > 0 ? $num:0;
            $data['log_list'] = $log_list;
        }

        //peopl中增加wx_name字段
        $temporary_people = isset($data['kanjia_info']['people']) ? $data['kanjia_info']['people'] : array();
        $temporary_members = isset($data['kanjia_info']['members']) ? $data['kanjia_info']['members'] : array();
        array_walk($temporary_members, function($member_id, $keys) use (&$temporary_people, $model_member){
            $wx_name = $model_member->getMemberWxInfo($member_id);
            $temporary_people[$keys]['wx_name'] = $wx_name;
        });
        $data['kanjia_info']['people'] = $temporary_people;

        output_data(array('kanjia_info'=> $data));
    }

    public function agreementOp() {
        $doc = Model('document')->getOneByCode('kanjia_doc');
        output_data($doc);
    }
    
    
    /**
     * 判断砍价是否重复
     * @author Harris
     * */
    private function isKanjiaOp($order,$buyer){
    	if(!in_array($buyer['member_id'],$order['kanjia_price']['members'])){
    		return true;
    	}else{
    		return false;
    	}
    }
    
    /**
     * 添加一条机器人砍价
     * @author Harris
     * @param  整个订单数组
     * */
    private function addRobot($order) {
    	$robot = Model("member")->getRobotList();
		array_push($order['kanjia_price']['members'], $robot['member_id']);
    	$user = array(
            "name" =>$robot['member_name'],
            "icon" =>getMemberAvatarHttps($robot['member_avatar']),
            "time" =>date("Y-m-d H:i:s")
		);

    	array_push($order['kanjia_price']['people'], $user);
		if($order['kanjia_price']['now'] < $order['kanjia_price']['total']) {
			$order['kanjia_price']['now'] += 1;
		}

		return $order;
    }
    
    /**
     * 添加一条用户砍价
     * @author Harris
     * @param  整个订单数组
     * */
    private function addKanjia($order, $buyer = array()){
    	array_push($order['kanjia_price']['members'], $buyer['member_id']);
		$user = array(
            "name" => $buyer['member_name'],
            "icon" => getMemberAvatarHttps($buyer['member_avatar']),
            "time" => date("Y-m-d H:i:s", TIMESTAMP)
		);
		array_push($order['kanjia_price']['people'], $user);
		return $order;
    }
    
    /**
     * 砍价接口
     * @author Harris
     * */
    public function kanjiaOp() {
    	if($_GET['key'] && ($order_id = $_GET['order_id'])) {
    		$buyer = Model("mb_user_token")->getMbUserTokenInfo(array("token"=>$_GET['key']));
    		$buyer?'':output_error(array("msg"=>"key有误"));
    		$order = Model("order_kanjia")->getKanjiaOrder(array('order_id'=>$order_id));
            //获取砍价会员信息  -- @author maolvxiansheng 
            $member_id = isset($buyer['member_id']) ? (int)$buyer['member_id'] : 0;
            $member_info = Model('member')->getMemberInfoByID($member_id, 'member_id,member_name,member_truename,member_avatar');
            if (empty($member_info)) output_error('请登录');

            //判断是否重复砍价
    		if($this->isKanjiaOp($order,$buyer)){
    			//判断是否已经砍价成功
    			if($order['kanjia_price']['now'] < $order['kanjia_price']['total']){
    				$update = array();
    				//添加用户砍价记录
	    			$order = $this->addKanjia($order, $member_info);
	    			//判断首次砍价，多送一次，加一条机器人记录
	    			$order['kanjia_price']['now']==1?$order=$this->addRobot($order):'';
	    			if($order['kanjia_price']['now'] < $order['kanjia_price']['total']) {
	    				$order['kanjia_price']['now'] += 1;
	    			}
	    			$update=array(
	    				"kanjia_price"=>json_encode($order['kanjia_price'], JSON_UNESCAPED_UNICODE)
	    			);
	    			//判断是否砍价完成
	    			$order['kanjia_price']['now']==$order['kanjia_price']['total']?$update['status']=1:'';
	    			$condition=array("order_id"=>$order_id);
	    			
	    			if(Model("p_kanjia")->editKanjiaOrder($update,$condition)){
                        //如果砍价完成就给买家发送砍价成功通知
                        if(!empty($update['status'])){
                            Logic('applet_notice')->appletKanjiaSuccess($order_id);
                        }
	    				output_data(array("msg"=>"砍价成功"));
	    			}else{
	    				output_error(array("msg"=>"砍价失败"));
	    			}
    			}else{
    				output_error(array("msg"=>"砍价已成功"));
    			}
    		}else{
    			output_error(array("msg"=>"该用户已经砍过了"));
    		}
    	}else{
    		output_error(array("msg"=>"缺少参数"));
    	}
    }
    
    public function testOp() {    	

    }

    /**
     * 查询是否已经砍价了
     * @author benald
     * */
    public function isKanjiaedOp() {
        if($_GET['key'] && ($order_id = $_GET['order_id'])) {
            $buyer = Model("mb_user_token")->getMbUserTokenInfo(array("token"=>$_GET['key']));
            $buyer?'':output_error(array("msg"=>"key有误"));
            $order = Model("order_kanjia")->getKanjiaOrder(array('order_id'=>$order_id));
            //获取砍价会员信息
            $member_id = isset($buyer['member_id']) ? (int)$buyer['member_id'] : 0;
            $member_info = Model('member')->getMemberInfoByID($member_id, 'member_id,member_name,member_truename,member_avatar');
            if (empty($member_info)) output_error('请登录');

            //判断是否重复砍价
            if($this->isKanjiaOp($order,$buyer)){
                output_data(array("msg"=>"该用户未砍过"));
            }else{
                output_error(array("msg"=>"该用户已经砍过了"));
            }
        }else{
            output_error(array("msg"=>"缺少参数"));
        }
    }
}
